<?php
namespace app\wx\controller;

use think\Controller;

class Reg extends Controller
{
    function index()
    {
        controller('Index')->_tpl();
        return $this->fetch('templates/wx/reg.html');
    }

    public function install_suite()
    {
        session('state',time());
        $wx_config=config('wx');
        $suite_id=$wx_config['suite_id'];
        $pre_auth_code=model('Qywx')->get_pre_auth_code();
        $json=json_decode($pre_auth_code,true);
        $redirect_uri=$wx_config['suite_redirect_uri'];
        $url='https://qy.weixin.qq.com/cgi-bin/loginpage?suite_id='.$suite_id.'&pre_auth_code='.$json['pre_auth_code'].'&redirect_uri='.$redirect_uri.'&state='.session('state');
        Header("HTTP/1.1 303 See Other");
        Header("Location: $url");
        exit;
    }

    public function suite_redirect_uri()
    {
        dump($_GET);
    }

    public function reg_member()
    {
        controller('Index')->_tpl();
        $qywx_user=session('qywx_user');
        if(empty($qywx_user))
        {
            jump('/wx/login');
        }

        $this->assign('qywx_user',$qywx_user);
        return $this->fetch('templates/wx/reg_member.html');

    }

    public function company_start()
    {
        $app=input('get.app');
        $qywx_user=session('qywx_user');
        if(empty($qywx_user))
        {
            jump('/wx/login');
        }
        $res=model('Reg')->company_start($app,$qywx_user['corp_info']['corpid']);
        if($res['res']==2)
        {
            jump('/wx/reg/reg_member.html');
        }
        if($res['res']==1)
        {
            jump('/wxadmin?app='.$app);
        }
    }

    function update_user_data()
    {
        if(empty(session('qywx_user'))||empty(session('cdb')))
        {
            return json(['res'=>false,'msg'=>'请登录']);
        }
        $app=session('nav')[0]['app'];
        $corpid=session('cdb')['corpid'];
        $res=model('reg')->copy_wx_dept($app,$corpid);
        if($res==false)
        {
            return json(['res'=>false,'msg'=>'同步企业部门失败']);
        }
        //同步用户信息开始
        $res=model('reg')->copy_wx_user($app,$corpid);
        if($res==false)
        {
            return json(['res'=>false,'msg'=>'同步企业用户失败']);
        }
        return json(['res'=>true,'msg'=>'同步成功，正在刷新页面']);
    }
}